const { DataTypes } = require("sequelize");
const sequelize = require("../db/connect");
const { Good, Sku } = require("./good");

const AppUser = sequelize.define("appUser", {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  //用户名
  username: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  //密码
  password: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  //介绍
  introduction: {
    type: DataTypes.STRING,
    allowNull: true,
  },
  //头像地址
  avatar: {
    type: DataTypes.STRING,
    allowNull: true,
  },

  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    updataValue: DataTypes.NOW,
  },
});

const Address = sequelize.define("address", {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  appUserId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  //联系人
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  //电话
  phone: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  //省份
  province: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  //城市
  city: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  //区
  district: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  // 具体地址
  detail: {
    type: DataTypes.STRING,
    allowNull: false,
  },
  //是否默认地址
  isDefault: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    updataValue: DataTypes.NOW,
  },
});

// 购物车
const Cart = sequelize.define("cart", {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    primaryKey: true,
  },
  //用户
  appUserId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  //商品
  goodId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  //规格
  skuId: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  //数量
  number: {
    type: DataTypes.INTEGER,
    allowNull: false,
  },
  createdAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
  },
  updatedAt: {
    type: DataTypes.DATE,
    allowNull: false,
    defaultValue: DataTypes.NOW,
    updataValue: DataTypes.NOW,
  },
});
// 建立一对多关系
AppUser.hasMany(Cart, { foreignKey: "appUserId" });
Cart.belongsTo(AppUser, { foreignKey: "appUserId" });

Good.hasMany(Cart, { foreignKey: "goodId" });
Cart.belongsTo(Good, { foreignKey: "goodId" });

Sku.hasMany(Cart, { foreignKey: "skuId" });
Cart.belongsTo(Sku, { foreignKey: "skuId" });

module.exports = {
  AppUser,
  Address,
  Cart,
};

